package com.baizhi.interceptor;

import com.baizhi.dto.UserDTO;
import com.baizhi.utils.RedisConstants;
import com.baizhi.utils.UserHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.获取sessionId
        String sessionId = request.getHeader("Authorization");
        if (StringUtils.isEmpty(sessionId)){
            //4.不存在，拦截，返回401状态码
            response.setStatus(401);
            return false;
        }
        UserDTO userDTO = (UserDTO)  redisTemplate.opsForValue().get(RedisConstants.LOGIN_USER_KEY + sessionId);
        if (ObjectUtils.isEmpty(userDTO)){
            //4.不存在，拦截，返回401状态码
            response.setStatus(401);
            return false;
        }
        UserHolder.saveUser(userDTO);
        return true;
    }

    //控制器执行完毕后执行该方法
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        UserHolder.removeUser();
    }
}
